package com.bonc.ioc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bonc.ioc.model.Knowledges;
import com.bonc.ioc.service.KnowledgesEsService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ZhangXu
 * @date 2021/4/24 19:17
 */
@Service
public class KnowledgesEsServiceImpl extends EsServiceImpl implements KnowledgesEsService {
    private static final Logger log = LoggerFactory.getLogger(KnowledgesEsServiceImpl.class);

    @Override
    public List<Knowledges> queryKnowledgesAssociation(String word) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //过滤失效数据：logstash每分钟同步数据库,通过同步时间筛选,过滤失效数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -3);
        Calendar afterTime = Calendar.getInstance();
        afterTime.add(Calendar.MINUTE, 3);
        // builder.must(QueryBuilders.rangeQuery("es_update_time").gte(sdf.format(beforeTime.getTime())).lte(sdf.format(new Date())).format("yyyy-MM-dd HH:mm:ss"));
        if (StringUtils.isNotBlank(word)) {
            builder.must(
                    QueryBuilders.boolQuery()
                            .should(QueryBuilders.matchQuery("keys", word))
            );
        }
        searchSourceBuilder.query(builder);

        //创建并设置SearchRequest对象
        SearchRequest searchRequest = new SearchRequest();
        //设置request要搜索的索引和类型
        searchRequest.indices("research_software");
        //设置SearchSourceBuilder查询属性
        searchRequest.source(searchSourceBuilder);
        log.info("ES检索命令 SearchSourceBuilder={}", searchSourceBuilder.toString());
        SearchResponse searchResponse = null;
        List<Knowledges> resultList = new LinkedList<>();
        try {
            searchResponse = client.search(searchRequest, COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert searchResponse != null;
        SearchHit[] hits = searchResponse.getHits().getHits();
        Arrays.stream(hits).forEach(hit -> {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Knowledges knowledges = BeanUtil.mapToBean(sourceAsMap, Knowledges.class, true);
            resultList.add(knowledges);
        });
        return resultList;
    }
}
